import { createSlice } from "@reduxjs/toolkit";
const tabSlice = createSlice({
  name: "tab",
  initialState: {
    isCollapse: false,
    tabList: [
      {
        path: "/",
        name: "home",
        label: "首页",
      },
    ],
    currentMenu: {},
  },
  reducers: {
    // 改变菜单栏缩小放大
    changeCollapse: (state) => {
      // console.log("state", state);
      state.isCollapse = !state.isCollapse;
    },
    //
    selectTagList: (state, { payload: val }) => {
      console.log("val", val);
      if (val.name !== "home") {
        // 如果是存在的tab就不添加
        const res = state.tabList.findIndex((item) => item.name == val.name);
        state.currentMenu = val;
        // console.log("res", res);
        if (res === -1) {
          state.tabList.push(val);
          console.log("state.tabList", state.tabList);
        }
      } else if (val.name !== "home" && state.tabList.length == 1) {
        state.currentMenu = {};
      }
    },
    setCurrentMenu: (state, { payload: val }) => {
      if (val.name == "home") {
        state.currentMenu = {};
      } else {
        state.currentMenu = val;
      }
    },
    closeTag: (state, { payload: val }) => {
      console.log("tabList", state.tabList);
      let res = state.tabList.findIndex((item) => item.name == val.name);
      console.log("res", res);
      state.tabList.splice(res, 1);
    },
  },
});

export const { changeCollapse, selectTagList, setCurrentMenu, closeTag } = tabSlice.actions;
export default tabSlice.reducer;
